package net.lcheng.service.impl;

import net.lcheng.dao.BaseVerificationCodeMapper;
import net.lcheng.model.BaseVerificationCode;
import net.lcheng.model.BaseVerificationCodeExample;
import net.lcheng.service.BaseVerificationCodeService;
import net.lcheng.utils.BaseVerificationCodeHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by zwr on 2016/6/28 0028.
 */
@Service
public class BaseVerificationCodeServiceImpl implements BaseVerificationCodeService {
    @Resource
    private BaseVerificationCodeMapper mapper;
    @Override
    public BaseVerificationCode getByPhoneAndCode(String phone, String code) {
        BaseVerificationCodeExample example = new BaseVerificationCodeExample();
        example.createCriteria().andPhoneEqualTo(phone).andCodeEqualTo(code);
        List<BaseVerificationCode> list = mapper.selectByExample(example);
        if(list!=null&&list.size()>0){
            return list.get(0);
        }else {
            return null;
        }
    }

    @Override
    public String insert(String phone, int type) {
        UUID uuid = UUID.randomUUID();
        String randStr = BaseVerificationCodeHelper.builder(false);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date createOn = calendar.getTime();
        calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE)+10);//验证码有效期10分钟
        Date expirationTime = calendar.getTime();
        //插入验证码
        BaseVerificationCode code = new BaseVerificationCode();
        code.setId(uuid.toString());
        code.setCode(randStr);
        code.setCreateOn(createOn);
        code.setExpirationTime(expirationTime);
        code.setIsUse(0);
        code.setPhone(phone);
        code.setType(type);
        mapper.insert(code);
        return randStr;
    }
}
